package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.utils.DateTimeUtil;
import com.mmall.utils.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ICategoryService iCategoryService;

    public ServerResponse saveOrUpdateProduct(Product product) {

        if (product != null) {
            if (product.getSubImages() != null) {
                String[] productImgsArray = product.getSubImages().split(",");
                product.setMainImage(productImgsArray[0]);
            }
            if (product.getId() != null) {
                int rowCount = productMapper.updateByPrimaryKey(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("更新产品成功");
                }
                return ServerResponse.createBySuccessMessage("更新产品失败");
            } else {
                int rowCount = productMapper.insert(product);
                if (rowCount > 0) {
                    return ServerResponse.createBySuccessMessage("新增产品成功");
                }
                return ServerResponse.createBySuccessMessage("新增产品失败");
            }
        }
        return ServerResponse.createByErrorMessage("新增产品参数错误");
    }

    public ServerResponse setSaleStatus(Integer productId, Integer status) {
        if (productId == null || status == null) {
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        int rowCount = productMapper.updateByPrimaryKeySelective(product);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("更新产品状态成功");
        }
        return ServerResponse.createBySuccessMessage("更新产品状态失败");
    }

    public ServerResponse<ProductDetailVo> managerProductDetail(Integer productId) {
        if (productId == null) {
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createBySuccessMessage("产品已下架或已删除");
        }
        ProductDetailVo detailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(detailVo);
    }

    private ProductDetailVo assembleProductDetailVo(Product product) {

        ProductDetailVo vo = new ProductDetailVo();
        vo.setId(product.getId());
        vo.setCategoryId(product.getCategoryId());
        vo.setSubtitle(product.getSubtitile());
        vo.setPrice(product.getPrice());
        vo.setMainImage(product.getMainImage());
        vo.setSubImages(product.getSubImages());
        vo.setDetail(product.getDetail());
        vo.setName(product.getName());
        vo.setStatus(product.getStatus());
        vo.setStock(product.getStock());
        // TODO: 2017/12/13 ftp服务器地址要改掉 
        vo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix",
                "http://10.211.55.4/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if (category != null) {

            vo.setParentCategoryId(category.getParentId());
        } else {
            vo.setParentCategoryId(0);
        }
        vo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        vo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdataTime()));
        return vo;
    }

    public ServerResponse getProductByPage(Integer pageNum, Integer pageSize) {

        //pageHelper-->startPage-->start
        PageHelper.startPage(pageNum, pageSize);
        //填充自己的sql查询逻辑
        List<Product> products = productMapper.selectList();
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : products) {
            ProductListVo vo = assembleProductListVo(product);
            productListVos.add(vo);
        }
        //pageHelper-->收尾
        PageInfo info = new PageInfo(products);
        info.setList(productListVos);
        return ServerResponse.createBySuccess(info);
    }

    private ProductListVo assembleProductListVo(Product product) {

        ProductListVo listVo = new ProductListVo();
        listVo.setCategoryId(product.getCategoryId());
        listVo.setId(product.getId());
        listVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix",
                "http://10.211.55.4/"));
        listVo.setMainImage(product.getMainImage());
        listVo.setName(product.getName());
        listVo.setPrice(product.getPrice());
        listVo.setStatus(product.getStatus());
        listVo.setSubtitle(product.getSubtitile());
        return listVo;
    }

    public ServerResponse<PageInfo> SearchProducts(String productName, Integer productId, Integer pageNum, Integer
            pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(productName)) {
            productName = new StringBuilder().append("%").append(productName).append("%").toString();
        }
        List<Product> productList = productMapper.selectProductByNameAndId(productName, productId);
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVo vo = assembleProductListVo(product);
            productListVos.add(vo);
        }
        PageInfo pageInfo = new PageInfo(productList);
        pageInfo.setList(productListVos);
        return ServerResponse.createBySuccess(pageInfo);
    }

    // protal

    public ServerResponse<ProductDetailVo> getProductDetail(Integer productId) {

        if (productId == null) {
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            return ServerResponse.createBySuccessMessage("产品已下架或已删除");
        }
        if (product.getStatus() != Const.ProductStatusEnum.ONSALE.getCode()) {
            return ServerResponse.createBySuccessMessage("产品已下架或已删除");
        }
        ProductDetailVo detailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(detailVo);
    }



    public ServerResponse<PageInfo> getProductByKeywordCategoryId(String keyword, Integer categoryId,
                                                                  Integer pageNum, Integer pageSize, String orderBy) {
        if (StringUtils.isBlank(keyword) && categoryId == null) {
            return ServerResponse.createByErrorMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),
                    ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        //存放当前分类以及当前分类下面的子分类的集合
        List<Integer> categoryIdlist = new ArrayList<>();
        if (categoryId != null) {

            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            if (category == null && StringUtils.isBlank(keyword)) {
                //如果没有该分类并且传过来的关键字是空字符串不报错
                PageHelper.startPage(pageNum, pageSize);
                List<ProductListVo> productListVoList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productListVoList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            categoryIdlist = iCategoryService.selectCategoryAndChildById(category.getId()).getData();
        }
        if (StringUtils.isNotBlank(keyword)) {
            keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
        }
        PageHelper.startPage(pageNum, pageSize);
        //排序跟前端约定用下划线分割前面是价格后面是排序的规则
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.ProductListOrderBy.PRICE_ASE_DESC.contains(orderBy)) {
                String[] orderByArr = orderBy.split("_");
                PageHelper.orderBy(orderByArr[0] + " " + orderByArr[1]);
            }
        }
        List<Product> productList = productMapper.selectProdutByNameAndCategoryIds(StringUtils.isBlank(keyword) ? null : keyword,
                categoryIdlist.size() == 0 ? null : categoryIdlist);
        List<ProductListVo> productListVos = Lists.newArrayList();
        for (Product product : productList) {
            ProductListVo listVo=assembleProductListVo(product);
            productListVos.add(listVo);
        }
        PageInfo pageInfo=new PageInfo(productList);
        pageInfo.setList(productListVos);
        return ServerResponse.createBySuccess(pageInfo);
    }
}
